package com.ltv.xiangqiplugin.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Vector;

public class SaveLoadUtil {
	private static final String CRLF = "\r\n";
	public static String savePGN(
			String event,
			String site,
			String date,
			String round,
			String red,
			String blue,
			String result,
			String initFen,
			Vector<String> moves) {
		
		StringBuffer sb = new StringBuffer();
		sb.append("[Event \"" + event + "\"]" + CRLF);
		sb.append("[Site \"" + site + "\"]" + CRLF);
		sb.append("[Date \"" + date + "\"]" + CRLF);
		sb.append("[Round \"" + round + "\"]" + CRLF);
		sb.append("[Red \"" + red + "\"]" + CRLF);
		sb.append("[Blue \"" + blue + "\"]" + CRLF);
		sb.append("[Result \"" + result + "\"]" + CRLF);
		sb.append("[InitPosition \"" + initFen + "\"]" + CRLF);
		sb.append(CRLF);
		
		int count = 1;
		for (int i = moves.size() - 1; i >=0; i = i - 2) {
			if (i - 1 >= 0) {
				sb.append(count + ". " + getStandardPGNMove(moves.get(i)) + " " + getStandardPGNMove(moves.get(i - 1)) + CRLF);
			} else {
				sb.append(count + ". " + getStandardPGNMove(moves.get(i)) + CRLF);
			}
			count++;
		}
		
		return sb.toString();
	}
	
	public static String getStandardPGNMove(String move) {
		String origin =move.substring(0, move.indexOf('-'));
		String destin = move.substring(move.indexOf('-')+1);
		
		return getStandardPGNCoor(origin) + '-' + getStandardPGNCoor(destin);
	}
	
	private static String getStandardPGNCoor(String coor) {
		int y = Integer.parseInt(coor.substring(1)) - 1;
		
		return coor.substring(0, 1) + y;
	}
	
	public static String getPGNMove(String move) {
		String origin =move.substring(0, move.indexOf('-'));
		String destin = move.substring(move.indexOf('-')+1);
		
		return getPGNCoor(origin) + '-' + getPGNCoor(destin);
	}
	
	private static String getPGNCoor(String coor) {
		int y = Integer.parseInt(coor.substring(1)) + 1;
		
		return coor.substring(0, 1) + y;
	}
	
	public static Vector<String> loadPGN(File file) throws Exception {
		// Read file
		InputStream is = new FileInputStream(file);
		InputStreamReader isr = new InputStreamReader(is);
		BufferedReader reader = new BufferedReader(isr);
		
		Vector<String> allMoves = new Vector<String>();
		
		try {
			String line = reader.readLine();
			while (line != null) {
				if (isMovesLine(line)) {
					String moves[] = line.split(" ");
					for (int i = 1; i < moves.length; i++) {
						if (isMove(moves[i])) {
							allMoves.add(getPGNMove(moves[i].toLowerCase()));
						}
					}
				}
				line = reader.readLine();
			}
		} finally {
			try {
				is.close();
			} catch (Exception e) {}
			try {
				isr.close();
			} catch (Exception e) {}
			try {
				reader.close();
			} catch (Exception e) {}
		}
		
		return allMoves;
	}
	
	public static String getInitFen(File file) throws Exception {
		// Read file
		InputStream is = new FileInputStream(file);
		InputStreamReader isr = new InputStreamReader(is);
		BufferedReader reader = new BufferedReader(isr);
		
		String ret = "";
		
		try {
			String line = reader.readLine();
			while (line != null) {
				if (line.trim().startsWith("[InitPosition")) {
					ret = line.replace("[InitPosition \"", "");
					ret = ret.replace("\"]", "");
					ret = ret.trim();
					break;
				}
				line = reader.readLine();
			}
		} finally {
			try {
				is.close();
			} catch (Exception e) {}
			try {
				isr.close();
			} catch (Exception e) {}
			try {
				reader.close();
			} catch (Exception e) {}
		}
		
		return ret;
	}
	
	public static Vector<String> loadAll(File file) throws Exception {
		return loadPGN(file);
	}
	
	private static boolean isMovesLine(String line) {
		return !(line.trim().startsWith("[") || line.trim().endsWith("]") || line.trim().equals(""));
	}
	
	private static boolean isCoor(String text) {
		if (text == null || text.length() < 2) {
			return false;
		}
		
		text = text.toLowerCase();
		
		try {
			char x = text.charAt(0);
			boolean isValidCoorX = (x == 'a' || x == 'b' || x == 'c' 
					|| x == 'd' || x == 'e' || x == 'f' || x == 'g' || x == 'h' || x == 'i');
			
			int y = Integer.parseInt(text.substring(1));
			boolean isValidCoorY = (y >= 0 && y <= 9);
			
			return isValidCoorX && isValidCoorY;
		} catch (Exception e) {
			return false;
		}
	}
	
	private static boolean isMove(String text) {
		if (text == null) {
			return false;
		}
		String coors[] = text.split("-");
		if (coors.length != 2) {
			return false;
		}
		
		return isCoor(coors[0]) && isCoor(coors[1]);
	}
	
	public static String getReversedFEN(String FEN) {
		String ret = "";
		String fields[] = FEN.split(" ");
		
		ret += getReversedString(fields[0]);
		
		if (fields.length > 1) {
			ret += " ";
			ret += fields[1];
		}
		
		return ret;
	}
	
	private static String getReversedString(String input) {
		return new StringBuffer(input).reverse().toString();
	}
}
